package com.bugsnag.ohos;

import ohos.aafwk.ability.RunningProcessInfo;
import ohos.app.Context;
import ohos.app.IAbilityManager;
import ohos.os.ProcessManager;

import com.bugsnag.ohos.annotation.Nullable;

import java.util.List;

/**
 * ForegroundDetector
 *
 * @since 2021-07-27
 */
class ForegroundDetector {
    @Nullable
    private final IAbilityManager abilityManager;

    ForegroundDetector(Context context) {
        this.abilityManager = context.getAbilityManager();
    }

    /**
     * Determines whether or not the application is in the foreground, by using the process'
     * importance as a proxy.
     * <p/>
     * In the unlikely event that information about the process cannot be retrieved, this method
     * will return null, and the 'inForeground' and 'durationInForeground' values will not be
     * serialized in API calls.
     *
     * @return whether the application is in the foreground or not
     */
    @Nullable
    boolean isInForeground() {
        RunningProcessInfo info = getProcessInfo();
        if (info != null) {
            return info.getWeight() == RunningProcessInfo.WEIGHT_FOREGROUND;
        }
        return false;
    }

    private RunningProcessInfo getProcessInfo() {
        if (abilityManager == null) {
            return null;
        }
        List<RunningProcessInfo> appProcesses = abilityManager.getAllRunningProcesses();
        if (appProcesses != null) {
            int pid = ProcessManager.getPid();
            for (RunningProcessInfo appProcess : appProcesses) {
                if (pid == appProcess.getPid()) {
                    return appProcess;
                }
            }
        }
        return null;
    }
}
